package com.baizhiedu.rsm.service.impl;

import com.baizhiedu.rsm.dao.AnswerDao;
import com.baizhiedu.rsm.dao.StudentDao;
import com.baizhiedu.rsm.dao.StudentMessageDao;
import com.baizhiedu.rsm.dao.SubjectDao;
import com.baizhiedu.rsm.dto.ShowAnswer;
import com.baizhiedu.rsm.entity.Answer;
import com.baizhiedu.rsm.entity.Student;
import com.baizhiedu.rsm.entity.StudentMessage;
import com.baizhiedu.rsm.entity.Subject;
import com.baizhiedu.rsm.service.AnswerService;
import com.baizhiedu.rsm.util.DateConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lby
 */
@Service
public class AnswerServiceImpl implements AnswerService {
    @Autowired
    private AnswerDao answerDao;
    @Autowired
    private SubjectDao subjectDao;
    @Autowired
    private StudentMessageDao studentMessageDao;


    @Override
    public String submitAnswer(Integer subjectId, String answerText, Integer studentId) {
        Answer answer = new Answer();
        try {
            answer.setAnswerdate(new DateConverter().convert(DateFormat.getDateInstance().format(new Date())));
            answer.setAnswertext(answerText);
            answer.setSubjectid(subjectId);
            answer.setStudentid(studentId);
            answerDao.insert(answer);
        }catch (Exception e){
            return "false";
        }
        return "true";
    }

    @Override
    public List<ShowAnswer> showAnswers(Date answerDate) {
        List<ShowAnswer> showAnswers = new ArrayList<ShowAnswer>();
        //1.根据日期获取当天所有的答案
        List<Answer> answers = answerDao.selectAnswersByDate(answerDate);
        for (Answer a:answers) {

            ShowAnswer showAnswer = new ShowAnswer();
            //2.获取对应的题目信息
            Subject subject = subjectDao.selectByPrimaryKey(a.getSubjectid());
            if(subject!=null){showAnswer.setSubjectText(subject.getContent());}
            //3.获取用户的名字
            StudentMessage student = studentMessageDao.selectByPrimaryKey(a.getStudentid());
            showAnswer.setAnswerName(student.getName());
            //4.获取答案
                //转化为markdown语法
//            MarkdownProcessor markdownProcessor = new MarkdownProcessor();
            showAnswer.setAnswerText(a.getAnswertext());
            //5.设置时间
            showAnswer.setAnswerDate(answerDate);
            //6.添加至list中
            showAnswers.add(showAnswer);
        }

        return showAnswers;
    }
}
